import { createRouter, createWebHistory } from 'vue-router';
import store from '@/store';
import FrameView from '@/views/FrameView.vue';
import HomeView from '@/views/home/Index.vue';
import { Local } from '@/utils/storage';

const routes = [
  {
    path: '/',
    name: 'default',
    component: FrameView,
    meta: {
      menuName: 'default',
      iconName: 'Memo',
    },
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: HomeView,
        meta: {
          menuName: '首页',
          iconName: 'Memo',
        },
      },
      {
        path: '/device',
        name: 'device',
        component: () => import('@/views/device/Index.vue'),
        meta: {
          menuName: '设备管理',
          iconName: 'Memo',
        },
        children: [],
      },
      {
        path: '/event',
        name: 'event',
        component: () => import('@/views/event/Index.vue'),
        meta: {
          menuName: '事件管理',
          iconName: 'Memo',
        },
        children: [
          {
            path: 'inspectionEvent',
            name: 'inspectionEvent',
            component: () => import('@/views/event/inspectionEvent/Index.vue'),
            meta: {
              menuName: '巡检事件管理',
              iconName: 'Memo',
            },
          },
          {
            path: 'realTimeEvent',
            name: 'realTimeEvent',
            component: () => import('@/views/event/realTimeEvent/Index.vue'),
            meta: {
              menuName: '实时事件管理',
              iconName: 'Memo',
            },
          },
        ],
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/Index.vue'),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach(async (to, from, next) => {
  // console.log('to', to.path, to.query, 'from', from.path, from.query);
  // 左侧菜单索引逻辑
  store.commit('setActiveMenuIndex', to.path);
  // 页面跳转拦截逻辑
  if (to.path == '/login') {
    // login页面不拦截
    next();
  } else {
    // 其他页面需要验证token
    let token = Local.get('token')
    if(token) {
      next();
    } else {
      next({ name: 'login' });
    }
    return;
  }
});
export default router;
